import os
import time
import subprocess
from .controller import Controller
from PIL import Image

class AndroidController(Controller):
    def __init__(self, adb_path, display):
        self.adb_path = adb_path
        self.display = display
    def show_border(self):
        user = self.get_user_by_display(self.display)
        command = self.adb_path + f" shell am start-foreground-service --user {user} -n ltd.qisi.autoguipilot/.BridgeService -a ACTION_SHOW_BORDER"
        subprocess.run(command, capture_output=True, text=True, shell=True)

    def hide_border(self):
        user = self.get_user_by_display(self.display)
        command = self.adb_path + f" shell am start-foreground-service --user {user} -n ltd.qisi.autoguipilot/.BridgeService -a ACTION_HIDE_BORDER"
        subprocess.run(command, capture_output=True, text=True, shell=True)

    def get_screenshot(self, save_path, display=0):
        command = self.adb_path + " shell rm /sdcard/screenshot.png"
        subprocess.run(command, capture_output=True, text=True, shell=True)
        time.sleep(0.5)
        command = f"{self.adb_path} shell screencap -d {self.display} -p /sdcard/screenshot.png"
        subprocess.run(command, capture_output=True, text=True, shell=True)
        time.sleep(0.5)
        command = self.adb_path + f" pull /sdcard/screenshot.png {save_path}"
        subprocess.run(command, capture_output=True, text=True, shell=True)

        # 1. 打开原图
        img = Image.open(save_path)
        # 2. 设置目标分辨率
        target_size = (1280, 720)
        # 3. 进行缩放（使用高质量算法）
        resized_img = img.resize(target_size, Image.LANCZOS)
        # 4. 保存输出文件
        resized_img.save(save_path)

        
        if not os.path.exists(save_path):
            return False
        else:
            return True

    def tap(self, x, y):
        print(f"111tap display {self.display}. x = {x},y = {y}")
        user = self.get_user_by_display(self.display)
        print(f"222tap display {self.display}. x = {x},y = {y}")
        command = self.adb_path + f" shell am start-foreground-service --user {user} -n ltd.qisi.autoguipilot/.BridgeService -a ACTION_SHOW_RIPPLE --ei x {x} --ei y {y}"
        subprocess.run(command, capture_output=True, text=True, shell=True)
        time.sleep(1)
        command = self.adb_path + f" shell input -d {self.display} tap {x} {y}"
        subprocess.run(command, capture_output=True, text=True, shell=True)

    def type(self, text):
        text = text.replace("\\n", "_").replace("\n", "_")
        for char in text:
            if char == ' ':
                command = self.adb_path + f" shell input -d {self.display} text %s"
                subprocess.run(command, capture_output=True, text=True, shell=True)
            elif char == '_':
                command = self.adb_path + f" shell input -d {self.display} keyevent 66"
                subprocess.run(command, capture_output=True, text=True, shell=True)
            elif 'a' <= char <= 'z' or 'A' <= char <= 'Z' or char.isdigit():
                command = self.adb_path + f" shell input -d {self.display} text {char}"
                subprocess.run(command, capture_output=True, text=True, shell=True)
            elif char in '-.,!?@\'°/:;()':
                command = self.adb_path + f" shell input -d {self.display} text \"{char}\""
                subprocess.run(command, capture_output=True, text=True, shell=True)
            else:
                user = self.get_user_by_display(self.display)
                command = self.adb_path + f" shell am broadcast --user {user} -a ADB_INPUT_TEXT --es msg \"{char}\""
                subprocess.run(command, capture_output=True, text=True, shell=True)

    def slide(self, x1, y1, x2, y2):
        command = self.adb_path + f" shell input -d {self.display} swipe {x1} {y1} {x2} {y2} 500"
        subprocess.run(command, capture_output=True, text=True, shell=True)

    def back(self):
        command = self.adb_path + f" shell input -d {self.display} keyevent 4"
        subprocess.run(command, capture_output=True, text=True, shell=True)

    def home(self):
        user = self.get_user_by_display(self.display)
        command = self.adb_path + f" shell am start --user {user} -a android.intent.action.MAIN -c android.intent.category.HOME"
        subprocess.run(command, capture_output=True, text=True, shell=True)

    def get_user_by_display(self, display):
        """根据 display 值返回对应的 user 值"""
        if display == 0:
            user = 10
        elif display == 1:
            user = 11
        else:
            # 处理其他情况，可以设置默认值或抛出异常
            user = None  # 或者 raise ValueError(f"不支持的 display 值: {display}")

        return user